import { infoList, commentTypeList } from '../../api/feedback'
import { resetObj } from '../../utils/resetObj'

const state = {
  commentDTO: {
    beginTime: '',
    commentType: '',
    endTime: '',
    index: 1,
    pageSize: 10
  },
  // 反馈类型列表
  typeList: [],
  date: '',
  feedbackList: [],
  total: +'',
  // 查看详情抽屉组件的显示和隐藏
  showDrawer: false,
  // 反馈详情
  feedbackDetail: {},
  // 要删除反馈的id
  deleteId: ''
}

const getters = {
  beginTime (state) {
    if (state.date === ('' || null || undefined)) {
      return ''
    } else {
      return state.date[0]
    }
  },
  endTime () {
    if (state.date === ('' || null || undefined)) {
      return ''
    } else {
      return state.date[1]
    }
  },
  // 最终上传的DTO
  DTO (state, getters) {
    const DTO = { ...state.commentDTO }
    if (DTO.index > 1 && state.feedbackList.length < 2) {
      DTO.index = DTO.index - 1
    }
    DTO.beginTime = getters.beginTime
    DTO.endTime = getters.endTime
    return DTO
  }
}

const mutations = {
  // 设置反馈类型列表
  set_typeList (state, list) {
    state.typeList = list
  },
  // 设置反馈列表
  set_feedbackList (state, list) {
    state.feedbackList = list
  },
  // 设置反馈总数
  set_total (state, total) {
    state.total = total
  },
  // 设置反馈页码
  set_commentDTO_index (state, index) {
    state.commentDTO.index = index
  },
  // 设置抽屉的显示和隐藏
  set_showDrawer (state, bool) {
    state.showDrawer = bool
  },
  // 设置反馈详情
  set_feedbackDetail (state, obj) {
    state.feedbackDetail = obj
  },
  // 设置删除id
  set_deleteId (state, id) {
    state.deleteId = id
  },
  // 设置类型
  set_commentType (state, type) {
    state.commentDTO.commentType = type
  }
}

const actions = {
  // 获取反馈类型列表
  getTypeList ({ commit }) {
    return new Promise((resolve, reject) => {
      commentTypeList().then(res => {
        if (res.data.data) {
          res.data.data.forEach(item => {
            if (!item.commentTypeId) {
              item.commentTypeId = ''
            }
          })
          commit('set_typeList', res.data.data)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 条件获取反馈列表
  getList ({ state, getters, commit }) {
    return new Promise((resolve, reject) => {
      infoList(getters.DTO)
        .then(res => {
          if (res.data.data) {
            commit('set_feedbackList', res.data.data.data)
            commit('set_total', res.data.data.count)
          }
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 重置查询条件
  reset ({ state }) {
    state.date = ''
    resetObj(state.commentDTO)
    state.commentDTO.index = 1
    state.commentDTO.pageSize = 10
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
